package com.example.online_forum.services.impl;

import com.example.online_forum.common.AppResult;
import com.example.online_forum.common.ResultCode;
import com.example.online_forum.dao.UserMapper;
import com.example.online_forum.exception.AppException;
import com.example.online_forum.model.User;
import com.example.online_forum.services.IUserService;
import com.example.online_forum.untils.MD5Util;
import com.example.online_forum.untils.StringUtil;
import com.example.online_forum.untils.UUIDUtil;
import com.sun.corba.se.spi.servicecontext.UEInfoServiceContext;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Override
    public void createNormalUser(User user) {
        if(user == null || StringUtil.isEmpty(user.getNickname()) || StringUtil.isEmpty(user.getUsername())
                ||StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getSalt())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询用户信息
        User existsuser = userMapper.selectByUserName(user.getUsername());
        //判断用户是否存在
        if(existsuser != null){
            //打印日志
            log.info(ResultCode.FAILED_USER_EXISTS.toString() + "username" + user.getUsername());
            //用户存在抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //用户的一些默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据库
        int row = userMapper.insertSelective(user);
        if(row != 1){
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //
            throw new AppException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户成功,username = " + user.getUsername()+". ");
    }

    @Override
    public User selectByUserName(String username) {
        if(StringUtil.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new AppException(AppResult.failed((ResultCode.FAILED_PARAMS_VALIDATE)));
        }
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //非空校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new  AppException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //按用户名查询用户信息
        User user = userMapper.selectByUserName(username);
        //对查询结果做非空校验
        if(user == null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new  AppException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //对密码校验
        String pw = MD5Util.md5Salt(password,user.getSalt());
        //与数据库的密码进行比较
        if(!pw.equals(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString() + ",密码错误,username = " + username);
            throw new  AppException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        return user;
    }

    @Override
    public User selectById(Long id) {
        if( id == null || id < 0 ){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new  AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id == null || id <= 0  ){
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        //查询数据库
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ",user id = " + id);
            throw new AppException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新帖子数量
        User updateuser = new User();
        updateuser.setId(user.getId());
        updateuser.setArticleCount(user.getArticleCount() + 1);
        int row = userMapper.updateByPrimaryKeySelective(updateuser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于 1");
            throw new AppException(AppResult.failed(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id == null || id <= 0){
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        //查询数据库
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ",user id = " + id);
            throw new AppException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }
        //更新用户发帖数量
        User updateuser = new User();
        updateuser.setId(user.getId());
        updateuser.setArticleCount(user.getArticleCount() - 1);
        //判断用户的发帖数量是否小于0
        if(updateuser.getArticleCount() < 0){
            updateuser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateuser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于 1");
            throw new AppException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 修改个人信息
     * @param user
     */
    @Override
    public void modifyInfo(User user) {
        if(user == null || user.getId() <= 0 || user.getId() == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_ARTICLE_COUNT.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_ARTICLE_COUNT));
        }
        //2.校验用户是否存在
        User existsuser = userMapper.selectByPrimaryKey(user.getId());
        if(existsuser == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //定义一个标志位
        boolean flag = false; // 为false表示没有通过
        // 对每一个参数进行校验
        //定义一个用来更新的对象,防止用户传入的User对象设置了其他的属性
        User updateUser = new User();
        //设置用户id
        updateUser.setId(user.getId());
        //对参数进行效验
        //校验用户名
        if(!StringUtil.isEmpty(user.getUsername()) && !user.getUsername().equals(existsuser.getUsername())){
            //更新用户名进行唯一性的校验
            User chekcUser = userMapper.selectByUserName(user.getUsername());
            if(chekcUser != null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                //抛出异常
                throw new AppException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //数据库中没有重复用户名
            updateUser.setUsername(user.getUsername());
            flag = true;
        }
        //校验昵称
        if(!StringUtil.isEmpty(user.getNickname())
                && !user.getNickname().equals(existsuser.getNickname())){
            //设置昵称
            updateUser.setNickname(user.getNickname());
            //更新标志位
            flag = true;
        }
        //校验性别
        if(user.getGender() != null && existsuser.getGender() != user.getGender()){
            updateUser.setGender(user.getGender());
            if(updateUser.getGender() > 2  || updateUser.getGender() < 0){
                updateUser.setGender((byte) 2);
            }
            //更新标志位
            flag = true;
        }
        //校验邮箱
        if(!StringUtil.isEmpty(user.getEmail())
                && !user.getEmail().equals(existsuser.getEmail())){
            //设置昵称
            updateUser.setEmail(user.getEmail());
            //更新标志位
            flag = true;
        }
        //校验电话号码
        if(! StringUtil.isEmpty(user.getPhoneNum())  && !user.getPhoneNum().equals(existsuser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标志位
            flag = true;
        }
        //校验个人简介
        if(! StringUtil.isEmpty(user.getRemark())  && !user.getRemark().equals(existsuser.getRemark())){
            updateUser.setRemark(user.getRemark());
            //更新标志位
            flag = true;
        }
        if(!flag){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.FAILED.toString() + ",受影响的行数不等于 1");
            throw new AppException(AppResult.failed(ResultCode.FAILED));
        }
    }

    /**
     * 修改密码操作
     * @param id
     * @param newPassword
     * @param oldPassword
     */
    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //校验参数
        if(id == null || id <= 0 || StringUtil.isEmpty(newPassword) || StringUtil.isEmpty(oldPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询要修改的用户信息
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null || user.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //对老密码进行加密
        String oldEncryptPwd = MD5Util.md5Salt(oldPassword,user.getSalt());
        //比较数据库中的密码
        if (!user.getPassword().equals(oldEncryptPwd)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new AppException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //生产新的盐值
        String salt = UUIDUtil.UUID_32();
        //生产新密码的密文
        String encryptPwd = MD5Util.md5Salt(newPassword,salt);
        //构造更新的对象
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setPassword(encryptPwd);
        updateUser.setSalt(salt);
        //调用dao层实现数据库写入
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new AppException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
}
